<?php

abstract class controller
{
	protected $task = null;	// 当前任务名

	protected $data = null;	// 保存 controller 数据
	protected $ajax = null;	// 保存 ajax 数据

	public function __construct()
	{
		$session = bone::get_session();
		if($session->has('controller.message'))
			$this->data['controller.message'] = $session->clear('controller.message');
	}

	public function execute($task = null)
	{
		if($task)
		{
			$this->task = $task;
			$this->$task();
		}
		else
			exit('传递 task 参数错误');
	}

	// 保存数据
	public function set_data($name, $value)
	{
		$this->data[$name] = $value;
	}

	public function get_data($name=null)
	{
		if($name)
			return $this->data[$name];
		else
			return $this->data;
	}

	// 转向， 并传递信息 $msg 
	// 信息类型, $type : notice:提示/warning:警告/error:错误
	public function redirect($url, $msg = null, $type='notice')
	{
		if($msg)
		{
			$session = bone::get_session();
			$message = new stdClass();
			$message->type = $type;
			$message->body = $msg;
			$session->set('controller.message', $message);
		}
		header('location:'.$url);
		exit;
	}


	// 设置 ajax 数据
	public function set_ajax($name, $value)
	{
		$this->ajax->$name = $value;
	}

	// ajax 输出
	public function ajax()
	{
		echo json_encode( $this->ajax );
		exit;
	}
	
}
